package cn.kgc.easybuy.listener;

import cn.kgc.easybuy.config.OrderListenByRedisConfig;
import cn.kgc.easybuy.pojo.Order;
import cn.kgc.easybuy.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

public class OrderExpirationListener extends KeyExpirationEventMessageListener {

    private OrderService orderService;

    private final static Logger logger = LoggerFactory.getLogger(OrderExpirationListener.class);

    private static final String ORDER_EXPIRE_KEY_PREFIX = "order:";

    private RedisTemplate redisTemplate;

    /**
     * 构造函数：必须传入Redis消息容器（父类要求），并注入业务Service
     */
    public OrderExpirationListener(RedisMessageListenerContainer listenerContainer, OrderService orderService, RedisTemplate redisTemplate) {
        super(listenerContainer);
        this.orderService = orderService;
        this.redisTemplate = redisTemplate;
    }

    /**
     * Redis键过期时触发
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取过期的Redis键
        String expiredRedisKey = message.toString();
        logger.info("Redis键过期事件触发，键：{}",expiredRedisKey);
        // 处理"order:"前缀的健
        // expiredRedisKey.startsWith(ORDER_EXPIRE_KEY_PREFIX)
        if (expiredRedisKey.length()>=38) {
            logger.info("处理订单超时未支付");
            //  解析出商户订单号（截取"order:"后面的字符串）
            int prefixIndex = expiredRedisKey.indexOf(ORDER_EXPIRE_KEY_PREFIX);
            String serialNumber = expiredRedisKey.substring(prefixIndex + ORDER_EXPIRE_KEY_PREFIX.length());

            logger.info("订单号: " + serialNumber);

            Order order = orderService.selectOrderBySerialNumber(serialNumber);

            // 获取订单id
            Integer id = order.getId();

            logger.info("订单id: " + id);
            try {
                // Order order = orderService.selectOrderById(id);
                // 取消超时未支付的订单
                boolean cancelSuccess = orderService.cancelOrder(id);
                if (cancelSuccess) {
                    logger.info("订单[" + id + "]因超时未支付,已自动取消");
                } else {
                    logger.info("订单[" + id + "]状态异常,取消失败（可能已支付/已取消）");
                }
            } catch (Exception e) {
                logger.error("处理过期订单时发生异常，订单ID: " + id, e);
            }
        }
    }
}
